package com.tingfeng.controller;

import com.tingfeng.config.response.ResultModel;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 通用，比如：获取用户信息，异常处理
 */
public class BaseController {
    private static final Logger logger = LogManager.getLogger(BaseController.class);

    /**
     * Requst data format is invalid
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseBody
    public Object handleMessageNotReadableException(HttpMessageNotReadableException ex, HttpServletRequest request, HttpServletResponse response) {

        if (ex instanceof HttpMessageNotReadableException) {
            return ResultModel.fail("请求数据格式异常");
        }

//        ex.printStackTrace();
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);

        logger.error("request data 发生异常，已记录", ex);

        return ResultModel.fail("出错啦，请重试");
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Object handleException(Exception ex, HttpServletRequest request, HttpServletResponse response) {

        if (ex instanceof MissingServletRequestParameterException) {
            return ResultModel.fail("缺少请求参数");
        }
        if (ex instanceof MethodArgumentTypeMismatchException) {
            return ResultModel.fail("方法参数类型不匹配");
        }
        if (ex instanceof HttpMediaTypeNotSupportedException) {
            return ResultModel.fail("不支持当前请求媒体类型");
        }
        if (ex instanceof IllegalStateException && ex.getMessage().contains("argument type mismatch")) {
            return ResultModel.fail("参数类型不匹配");
        }

//        ex.printStackTrace();
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

        logger.error("发生异常，已记录", ex);

        return ResultModel.fail("出错啦，请重试");
    }


}
